# -*- coding: UTF-8 -*-
# @Project ：VehicleDimensionMeasurementSystem 
# @File    ：process_file.py
# @IDE     ：PyCharm 
# @Date    ：2024/6/12 下午9:58


import os.path
import time
import configparser
from typing import Dict


class CustomFileException(Exception):
    """公共方法自定义异常处理"""

    def __init__(self, state, message):
        super().__init__(message)
        self.state = state
        self.message = message


class ProcessConfigParser:
    config = configparser.ConfigParser()

    def build_request_ini(self, path: str, trailer=0, vehicle_type='', vehicle_model='', history_mode=1):
        """生成开启测量请求文件"""
        self.config['请求类型'] = {'RequestType': '1'}
        self.config['测量项目'] = {'LWH': 1,
                                   'Wheelbase': trailer,  # 挂车模式1挂车、0普通车、6单挂模式
                                   'InnerHeiMode': 0,
                                   'SpecialMode': 0,
                                   'cllx': vehicle_type,  # 车辆类型
                                   'clxh': vehicle_model,  # 车辆型号
                                   'HistoryMode': history_mode}
        with open(path, 'w') as file:
            self.config.write(file)

    def wait_measure_result(self, file_name: str, waiting_time=60) -> dict[str, str]:
        """等待检测结果"""
        count = 0  # 用于计时，每0.5秒钟计一次
        while waiting_time > count:
            time.sleep(0.5)  # 每间隔一秒执行一次
            count += 0.5
            if not os.path.exists(file_name):
                continue
            self.config.read(file_name)
            if not self.config.has_section('测量项目'):
                raise CustomFileException(state=3000, message='结果文件读取失败，请检查结果文件是否正确')
            return {key: value for key, value in self.config.items('测量项目')}


